package ibatis;

import gui.common.msg.MsgType;
import gui.common.msg.SysMessage;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import com.ibatis.sqlmap.client.SqlMapClient;


import data.Count;
import data.Forum;
import data.Group;
import data.dao.ForumDao;

public class SqlMapForumDao implements ForumDao{
	
	private SqlMapClient sd=SqlConfig.getSqlMapInstance();
	
	public SysMessage createNewForum(Forum forum) throws SQLException {
		SysMessage msg=new SysMessage();
		if(forum.getId()<1){
			int seed=SeedProvider.getSeed(Forum.SeedName);
			forum.setId(seed);
		}
		if(forum.getTime()==null){
			forum.setTime(new Date(System.currentTimeMillis()));
		}
		msg.subject="Create Forum";
		try{
			sd.insert("insertForum", forum);
			msg.detail="create forum success!";
			msg.data=forum;
		}catch (Exception e) {
			e.printStackTrace();
			msg.type=MsgType.Error;
			msg.detail=e.getMessage();
			msg.data=null;
		}
		return msg;
	}

	public SysMessage deleteForum(Forum forum) throws SQLException {
		SysMessage msg=new SysMessage();
		msg.subject="Delete Forum";
		try {
			sd.delete("deleteForum",forum);
			msg.detail="delete forum success!";
		} catch (Exception e) {
			e.printStackTrace();
			msg.detail=e.getMessage();
			msg.type=MsgType.Error;
		}
		return msg;
	}

	public Count getForumCount(Group group) throws SQLException {
		Count count=null;
		try {
			count=(Count)sd.queryForObject("getForumCount", group);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return count;
	}

	public List<Forum> getForumList(Group group) throws SQLException {
		List<Forum> result=null;
		try {
			result=(List<Forum>)sd.queryForList("getForumList", group);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	public List<Forum> getForumList(Group group, int start, int end)
			throws SQLException {
		List<Forum> result=null;
		try {
			result=(List<Forum>)sd.queryForList("getForumList", group,start,end);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	public SysMessage updateForum(Forum forum) throws SQLException {
		SysMessage msg=new SysMessage();
		forum.setTime(new Date(System.currentTimeMillis()));
		msg.subject="Update forum";
		try {
			sd.update("updateForum", forum);
			msg.type=MsgType.Success;
			msg.detail="Update forum info success";
		} catch (Exception e) {
			e.printStackTrace();
			msg.type=MsgType.Error;
			msg.detail=e.getMessage();
		}
		return msg;
	}

	public Forum getForumById(int id) throws SQLException {
		Forum forum=null;
		try {
			forum=(Forum)sd.queryForObject("getForumById", id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return forum;
	}

	

}
